package com.jianan.mis.app;

import java.lang.reflect.InvocationTargetException;

import org.eclipse.core.runtime.IPlatformRunnable;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.Platform;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.PlatformUI;

import com.jianan.mis.app.login.LoginDialog;
import com.jianan.mis.app.login.LoginStatus;
import com.jianan.mis.data.cache.CountryCache;
import com.jianan.mis.data.cache.EmployeeCache;
import com.jianan.mis.data.cache.IntermanCache;
import com.jianan.mis.data.domain.Session;
import com.jianan.mis.data.domain.User;
import com.jianan.mis.service.OsConsultationService;
import com.jianan.mis.service.SecurityService;
import com.jianan.mis.sys.IMessageKeys;
import com.jianan.mis.sys.SpringBeanFactory;

/**
 * This class controls all aspects of the application's execution
 */
public class Application implements IPlatformRunnable {

	private SecurityService securityService;
	
	// 登陆用户
	private User user;

	// 登陆状态
	private LoginStatus loginStatus;

	// 是否自动登陆
	boolean auto_login;
	
	// 启动自动尝试登陆
	boolean firstTry = true;

	public Object run(Object args) throws Exception {
		
		Display display = PlatformUI.createDisplay();
		try {
			// 初始化Spring
			SpringBeanFactory.initialize();
			securityService = (SecurityService) SpringBeanFactory.getBean("securityService");
			if(securityService == null) {
				return IPlatformRunnable.EXIT_OK;
			}
			Platform.endSplash();

			// 登陆
			loginStatus = new LoginStatus();
			while (!login()) {
				if (loginStatus.isExit() == true)
					return IPlatformRunnable.EXIT_OK;
				MessageDialog.openError(null, IMessageKeys.LOGIN_FAIL,
						loginStatus.getFailCause());
				loginStatus.setDone(false);
			}
			
			preWork();

			int returnCode = PlatformUI.createAndRunWorkbench(display,
					new ApplicationWorkbenchAdvisor());
			if (returnCode == PlatformUI.RETURN_RESTART) {
				return IPlatformRunnable.EXIT_RESTART;
			}
			return IPlatformRunnable.EXIT_OK;
		} finally {
			display.dispose();
		}
	}

	/**
	 * 登陆方法
	 * 
	 * @return
	 */
	private boolean login() {
		LoginDialog loginDialog = new LoginDialog(null);

		if (!auto_login || !firstTry || loginDialog.getUser() == null) {
			if (loginDialog.open() != Window.OK) {
				loginStatus.setExit(true);
				return false;
			}
		}

		firstTry = false;
		user = loginDialog.getUser();
		while (loginStatus.isDone() == false)
			loginWithProgress();

		return loginStatus.isSuccessful();
	}

	private void loginWithProgress() {
		ProgressMonitorDialog progress = new ProgressMonitorDialog(null);
		try {
			progress.run(true, true, new IRunnableWithProgress() {
				@SuppressWarnings("unchecked")
				public void run(IProgressMonitor monitor)
						throws InvocationTargetException {
					try {
						monitor.beginTask("用户验证...", IProgressMonitor.UNKNOWN);

						// 测试代码
						if (securityService.login(user.getUsername(), user
								.getPassword())) {
							Session.getInstance().setEmployee(securityService.findEmployee(user.getUsername()));
							loginStatus.setSuccessful(true);
						} else {
							loginStatus.setFailCause(IMessageKeys.NONEXISTING_USER_OR_WRONG_PWD);
						}

						monitor.done();
					} catch (Exception e) {
						throw new InvocationTargetException(e);
					}
				}
			});
			loginStatus.setDone(true);
		} catch (Exception e) {
			e.printStackTrace();
			loginStatus.setDone(true);
			loginStatus.setExit(true);
			loginStatus.setFailCause(e.getMessage());
		}
	}
	
	public void preWork() {
		EmployeeCache.getInstance();
		CountryCache.getInstance();
		IntermanCache.getInstance();
		OsConsultationService osConsultationService = (OsConsultationService) SpringBeanFactory
				.getBean("osConsultationService");
		// 设置过期咨询表状态
		osConsultationService.updateExpired();
		//OsContractService osContractService = (OsContractService) SpringBeanFactory
		//		.getBean("osContractService");
		// 设置过期签约表状态
		//osContractService.updateExpired();
	}
}
